import CryptoJS from 'crypto-js';

const key = CryptoJS.enc.Utf8.parse('YunQiHuiZhi&$YZS'); //秘钥
var iv = CryptoJS.enc.Utf8.parse('YiZhanShi$GuanLi'); //偏移量

/**
 * AES加密
 * @param word 加密对象
 * @param secretKey 秘钥
 * @param ivString 偏移量
 * @returns
 */
export const EncryptIv = (word: any, secretKey: any = key, ivString: any = iv) => {
  let srcs = CryptoJS.enc.Utf8.parse(word);

  let key = CryptoJS.enc.Utf8.parse(secretKey);
  let iv = CryptoJS.enc.Utf8.parse(ivString);

  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.ciphertext.toString().toUpperCase();
};

/**
 * AES解密
 * @param word 解密对象
 * @param secretKey 秘钥
 * @param ivString 偏移量
 * @returns
 */
export const DecryptIv = (word: any, secretKey: any = key, ivString: any = iv) => {
  let key = CryptoJS.enc.Utf8.parse(secretKey);
  let iv = CryptoJS.enc.Utf8.parse(ivString);

  let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  let decrypt = CryptoJS.AES.decrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);

  return decryptedStr.toString();
};

/**
 * AES 加密 用的后端返回的秘钥
 * @param word 加密对象
 * @param secretKey 秘钥
 * @returns
 */
export const Encrypt = (word: any, secretKey: any) => {
  let encryptKey = CryptoJS.enc.Utf8.parse(secretKey);
  let encrypted = CryptoJS.AES.encrypt(word, encryptKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
};

/**
 * AES 解密 用后端返回秘钥
 * @param word 解密对象
 * @param secretKey 秘钥
 * @returns
 */
export const Decrypt = (word: any, secretKey: any) => {
  let dDecryptKey = CryptoJS.enc.Utf8.parse(secretKey);
  let decrypt = CryptoJS.AES.decrypt(word, dDecryptKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
};
